package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;

import java.io.File;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityCameraBinding;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.WorkPathUtil;

public class CameraActivity extends BaseAc<ActivityCameraBinding> {

    //相机设置
    private boolean isFlash = false;//判断是否打开闪光灯
    private CameraOptions mCameraOptions;
    private Handler mHandler;
    private int mRecordTime;//拍摄视频的时间
    private boolean isShoot = false;

    @Override
    protected int onCreate() {
        return R.layout.activity_camera;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCameraBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivCameraReversal.setOnClickListener(this);
        mDataBinding.ivCameraStart.setOnClickListener(this);
        mDataBinding.ivCameraFlash.setOnClickListener(this);
        mDataBinding.tvCameraPicture.setOnClickListener(this);
        mDataBinding.tvCameraVideo.setOnClickListener(this);
        mHandler = new Handler();
        mRecordTime = 0;
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivCameraReversal://镜头反转
                reversalLens();
                break;
            case R.id.ivCameraFlash:
                //闪光灯
                openFlash();
                break;
            case R.id.ivCameraStart://开始拍摄
                startShot();
                break;
            case R.id.tvCameraPicture://拍摄图片模式
                isShoot = false;
                mDataBinding.llVideoLog.setVisibility(View.GONE);
                mDataBinding.tvCameraPicture.setVisibility(View.INVISIBLE);
                mDataBinding.tvCameraVideo.setVisibility(View.VISIBLE);
                mDataBinding.tvCameraMode.setText(R.string.shoot_picture);
                mDataBinding.cameraView.setMode(Mode.PICTURE);
                mDataBinding.ivCameraStart.setImageResource(R.drawable.icon_ps);
                break;
            case R.id.tvCameraVideo://拍摄视频模式
                getRecordPermission();
                break;
        }
    }

    @Override
    protected void initData() {
        getPermission();
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_pic_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }
        }).request();
    }

    private void getRecordPermission() {
        StkPermissionHelper.permission(Manifest.permission.RECORD_AUDIO).reqPermissionDesc(getString(R.string.get_camera_video_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                isShoot = true;
                mDataBinding.llVideoLog.setVisibility(View.VISIBLE);
                mDataBinding.tvVideoNum.setText("00:00");
                mDataBinding.tvVideoNum.setTextColor(Color.parseColor("#80FFFFFF"));
                mDataBinding.tvCameraPicture.setVisibility(View.VISIBLE);
                mDataBinding.tvCameraVideo.setVisibility(View.INVISIBLE);
                mDataBinding.tvCameraMode.setText(R.string.shoot_video);
                mDataBinding.cameraView.setMode(Mode.VIDEO);
                mDataBinding.cameraView.setAudio(Audio.ON);
                mDataBinding.ivCameraStart.setImageResource(R.drawable.icon_lz);
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {
                mCameraOptions = options;
            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                //获取图片 去到预览界面
                int picWidth = result.getSize().getWidth();
                int picHeight = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (picWidth * picHeight > screenWidth * screenHeight) {
                    picWidth = screenWidth;
                    picHeight = screenHeight;
                }
                result.toBitmap(picWidth, picHeight, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        //保存到相册
                        ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {
                //开始拍摄视频
                startRecordTime();
            }

            @Override
            public void onVideoRecordingEnd() {
                //视频拍摄结束
                mDataBinding.tvVideoNum.setText("00:00");
                mDataBinding.tvVideoNum.setTextColor(Color.parseColor("#80FFFFFF"));
                stopRecordTime();
            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {
                //保存到相册
                FileP2pUtil.copyPrivateVideoToPublic(mContext, result.getFile().getPath());
            }
        });
    }

    //反转镜头
    private void reversalLens() {
        Facing curFacing = mDataBinding.cameraView.getFacing();
        if (curFacing == Facing.BACK) {
            mDataBinding.cameraView.setFacing(Facing.FRONT);
        } else {
            mDataBinding.cameraView.setFacing(Facing.BACK);
        }
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.icon_sgd2);
            shotTipText(getString(R.string.flash_close));
            mDataBinding.cameraView.setFlash(Flash.OFF);
        } else {
            isFlash = true;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.icon_sgd1);
            shotTipText(getString(R.string.flash_open));
            mDataBinding.cameraView.setFlash(Flash.TORCH);
        }
    }


    //显示提示文字
    private void shotTipText(String text) {
        mDataBinding.tvCameraTipText.setText(text);
        mDataBinding.tvCameraTipText.setVisibility(View.VISIBLE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mDataBinding.tvCameraTipText.setVisibility(View.GONE);
            }
        }, 500);
    }

    //开始拍摄
    private void startShot() {
        if (!isShoot) {//照片拍摄
            if (mDataBinding.cameraView.isTakingPicture()) return;
            mDataBinding.cameraView.takePictureSnapshot();
        } else {//视频拍摄
            if (mDataBinding.cameraView.isTakingVideo()) {
                mDataBinding.cameraView.stopVideo();
            } else {
                String filePath = WorkPathUtil.generateVideoFilePath(null);
                if (filePath != null) {
                    mDataBinding.cameraView.takeVideoSnapshot(new File(filePath));
                    mDataBinding.tvVideoNum.setTextColor(Color.parseColor("#FFFFFF"));
                }
            }
        }
    }

    //开始拍摄视频
    private void startRecordTime() {
        mRecordTime = 0;
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
        mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
    }

    //结束拍摄视频
    private void stopRecordTime() {
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
    }

    private final Runnable mUpdateRecordTimeTask = new Runnable() {
        @Override
        public void run() {
            mRecordTime++;
            mDataBinding.tvVideoNum.setText(TimeUtils.millis2String(mRecordTime * 1000L, "mm:ss"));
            mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
        }
    };

}